/**
 * Sub-Agent Selector Component
 * 
 * Allows users to select which sub-agent to use for the conversation
 */

import { useState, useEffect } from 'react';
import { Bot, ChevronDown, Sparkles } from 'lucide-react';
import { Button } from '../ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '../ui/dropdown-menu';
import { Badge } from '../ui/badge';

export interface SubAgent {
  id: string;
  name: string;
  description: string;
  category?: string;
  isBuiltin?: boolean;
}

interface SubAgentSelectorProps {
  selectedSubAgent: SubAgent | null;
  onSelect: (subAgent: SubAgent | null) => void;
  disabled?: boolean;
}

export function SubAgentSelector({
  selectedSubAgent,
  onSelect,
  disabled = false,
}: SubAgentSelectorProps) {
  const [subAgents, setSubAgents] = useState<SubAgent[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchSubAgents();
  }, []);

  const fetchSubAgents = async () => {
    try {
      const response = await fetch('http://localhost:3000/api/subagents');
      const data = await response.json();

      if (data.success) {
        setSubAgents(data.data.subagents || []);
      }
    } catch (error) {
      console.error('Failed to fetch sub-agents:', error);
    } finally {
      setLoading(false);
    }
  };

  const groupedSubAgents = subAgents.reduce((acc, agent) => {
    const category = agent.category || 'other';
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(agent);
    return acc;
  }, {} as Record<string, SubAgent[]>);

  const categoryLabels: Record<string, string> = {
    development: '开发',
    testing: '测试',
    security: '安全',
    documentation: '文档',
    database: '数据库',
    devops: 'DevOps',
    design: '设计',
    analysis: '分析',
    other: '其他',
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          disabled={disabled || loading}
          className="gap-2"
        >
          {selectedSubAgent ? (
            <>
              <Bot className="h-4 w-4" />
              <span className="max-w-[150px] truncate">{selectedSubAgent.name}</span>
              {selectedSubAgent.isBuiltin && (
                <Badge variant="secondary" className="ml-1 h-5 px-1 text-xs">
                  内置
                </Badge>
              )}
            </>
          ) : (
            <>
              <Sparkles className="h-4 w-4" />
              <span>通用助手</span>
            </>
          )}
          <ChevronDown className="h-4 w-4 opacity-50" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-[300px]">
        <DropdownMenuLabel>选择 Sub-Agent</DropdownMenuLabel>
        <DropdownMenuSeparator />

        {/* Default option */}
        <DropdownMenuItem
          onClick={() => onSelect(null)}
          className="cursor-pointer"
        >
          <div className="flex items-center gap-2">
            <Sparkles className="h-4 w-4" />
            <div>
              <div className="font-medium">通用助手</div>
              <div className="text-xs text-muted-foreground">
                使用默认的 Claude 助手
              </div>
            </div>
          </div>
        </DropdownMenuItem>

        <DropdownMenuSeparator />

        {/* Grouped sub-agents */}
        {Object.entries(groupedSubAgents).map(([category, agents]) => (
          <div key={category}>
            <DropdownMenuLabel className="text-xs text-muted-foreground">
              {categoryLabels[category] || category}
            </DropdownMenuLabel>
            {agents.map((agent) => (
              <DropdownMenuItem
                key={agent.id}
                onClick={() => onSelect(agent)}
                className="cursor-pointer"
              >
                <div className="flex items-center gap-2">
                  <Bot className="h-4 w-4" />
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{agent.name}</span>
                      {agent.isBuiltin && (
                        <Badge variant="secondary" className="h-4 px-1 text-[10px]">
                          内置
                        </Badge>
                      )}
                    </div>
                    <div className="text-xs text-muted-foreground line-clamp-1">
                      {agent.description}
                    </div>
                  </div>
                </div>
              </DropdownMenuItem>
            ))}
            <DropdownMenuSeparator />
          </div>
        ))}

        {loading && (
          <div className="p-4 text-center text-sm text-muted-foreground">
            加载中...
          </div>
        )}

        {!loading && subAgents.length === 0 && (
          <div className="p-4 text-center text-sm text-muted-foreground">
            暂无可用的 Sub-Agents
          </div>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

